/**
 * Program   :   LoginAuthenticationFilter.java
 * Author    :   shadow guo
 * Create    :   2013-6-12 上午12:58:08
 *
 * Copyright 2008 by Tongfu Information Technology Co. Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Tongfu Information Technology Co. Ltd. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Tongfu Information Technology Co. Ltd.
 * 
 */
package com.tongfusoft.web.core.security;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.tongfusoft.utils.UIDGeneratorService;
import com.tongfusoft.utils.web.WebUtils;
import com.tongfusoft.web.core.Constant;
import com.tongfusoft.web.core.data.TLogs;
import com.tongfusoft.web.core.data.User;
import com.tongfusoft.web.core.service.ILogService;
import com.tongfusoft.web.core.service.ISecurityService;

public class LoginAuthenticationFilter extends
		UsernamePasswordAuthenticationFilter {
	private ISecurityService securityService;
	private ILogService logService;
	
	public ILogService getLogService() {
		return logService;
	}

	public void setLogService(ILogService logService) {
		this.logService = logService;
	}

	public ISecurityService getSecurityService() {
		return securityService;
	}

	public void setSecurityService(ISecurityService securityService) {
		this.securityService = securityService;
	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {

		String userName = this.obtainUsername(request);
		String userPwd = this.obtainPassword(request);

		if (userName == null || userName.trim().equals("")) {
			throw new BadCredentialsException("账户不能为空");
		}
		if (userPwd == null || userPwd.trim().equals("")) {
			throw new BadCredentialsException("密码不能为空");
		}
		
		Map params = WebUtils.getRequestParameters(request);
		params.putAll(WebUtils.getApplicationAttributes(request));
		
		if(this.getSecurityService().validateUser(params)){
			User user = this.getSecurityService().getUserInfo(userName);
			request.getSession().setAttribute(Constant.SESSION_USER, user);
			
			//获取需要填充到session中值
			Map<String, Object> sessionParam;
			try {
				sessionParam = this.getSecurityService().getPredefineContent(user, params);
				Iterator<Entry<String,Object>> iter = sessionParam.entrySet().iterator();
				while(iter.hasNext()){
					Entry<String,Object> entry = iter.next();
					request.getSession().setAttribute(entry.getKey(), entry.getValue());
				}
			} catch (Exception e) {
				throw new BadCredentialsException(e.getMessage());
			}
			
			
			//记录日志
			TLogs tLog = getLog(user);
			this.getLogService().log(tLog);
			
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
					userName, user.getUserPasswrod(),this.getSecurityService().loadUserAuthoritiesByName(userName));
			this.setDetails(request, authRequest);
			
			return this.getAuthenticationManager().authenticate(authRequest);
			
		}else{
			throw new BadCredentialsException("验证不通过");
		}

		/*if(StringUtils.equals(CryptoUtils.getMD5(userPwd), this.getSecurityService().getPwdByName(userName))){
			User user = this.getSecurityService().getUserInfo(userName);
			request.getSession().setAttribute(Constant.SESSION_USER, user);
			
			//记录日志
			TLogs tLog = getLog(user);
			this.getLogService().log(tLog);
			
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
					userName, user.getUserPasswrod(),this.getSecurityService().loadUserAuthoritiesByName(userName));
			this.setDetails(request, authRequest);
			
			return this.getAuthenticationManager().authenticate(authRequest);
		}else{
			throw new BadCredentialsException("用户名和密码不匹配");
		}*/
	}
	
	private TLogs getLog(User user){
		TLogs tLog = new TLogs();
		tLog.setLogId(UIDGeneratorService.getUUID());
		tLog.setCreatedBy(user.getPkValue());
		tLog.setOperName(user.getUserDisplayName());
		tLog.setOperType("login");
		tLog.setMethodName(this.getClass().getName()+".attemptAuthentication");
		tLog.setLogContent("登录系统");
		tLog.setOperResult("1"); //成功
		tLog.setParamsContent("");
		
		return tLog;
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		return super.obtainPassword(request);
	}

	@Override
	protected String obtainUsername(HttpServletRequest request) {
		return super.obtainUsername(request);
	}

	@Override
	protected void setDetails(HttpServletRequest request,
			UsernamePasswordAuthenticationToken authRequest) {
		super.setDetails(request, authRequest);
	}
}
